package com.betterwood.dragon.dao.enhances.impl;

import com.betterwood.dragon.dao.enhances.CustomeResultRepo;
import com.betterwood.dragon.entity.Result;
import com.betterwood.dragon.entity.dto.SearchDTO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import java.util.regex.Pattern;

/**
 * @author dominic
 * @create 2021-06-09 13:59
 */
@Slf4j
public class CustomeResultRepoImpl implements CustomeResultRepo {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<Result> insertResults(List<Result> resultList) {
        return (List<Result>) mongoTemplate.insert(resultList, Result.class);
    }

    @Override
    public Page<Result> findBySearchDto(SearchDTO searchDto, Pageable pageable) {
        Query query = new Query().with(pageable);
        log.info(searchDto.toString());

        if (StrUtil.isNotBlank(searchDto.getId())) {

            query.addCriteria(where("searchId").is(searchDto.getId()));
        }
        if (!StrUtil.equals(searchDto.getProp(), "EMPTY")) {

            Pattern pattern = Pattern.compile("^.*" + searchDto.getProp() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(where("prop").regex(pattern));
        }

        if (!StrUtil.equalsAny(searchDto.getSiteNo(), "EMPTY", "ALL")) {
        
            query.addCriteria(where("siteNo").is(searchDto.getSiteNo()));
        }

        if (!StrUtil.equals(searchDto.getMaker(), "EMPTY")) {

            Pattern pattern = Pattern.compile("^.*" + searchDto.getMaker() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(where("maker").regex(pattern));
        }

        List<Result> results = mongoTemplate.find(query, Result.class);

        return PageableExecutionUtils.getPage(results, pageable,
                () -> mongoTemplate.count(Query.of(query).limit(-1).skip(-1), Result.class));
    }

}
